import json
import os
import requests
from utils.readutil import Readdata
from utils.logutil import getlog


class ApiClient:
    def __init__(self):
        self.api_url_path = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "config",
                                         "setting.ini")
        self.api_url = Readdata().read_ini(self.api_url_path)["host"]["api_url"]
        self.session = requests.Session()

    def do_request(self, url, method, **kwargs):
        result = self.request(self.api_url + url, method, **kwargs).json()
        getlog.info("接口返回的报文是：>>>>>>>>>>>>>>>>>>>>\n{}".format(json.dumps(result, indent=2, ensure_ascii=False)))
        return result

    def request(self, url, method, **kwargs):
        self.request_log(url, method, **kwargs)
        if method == "GET":
            return self.session.get(url, **kwargs)
        if method == "POST":
            return self.session.post(url, **kwargs)
        if method == "PUT":
            return self.session.put(url, **kwargs)
        if method == "DELETE":
            return self.session.delete(url, **kwargs)

    def request_log(self, url, method, **kwargs):
        getlog.info(f"接口的地址是：>>>>>>>>>>>>>>>>>>>>>{url}")
        getlog.info(f"接口的方法是：>>>>>>>>>>>>>>>>>>>>>{method}")
        data = dict(**kwargs).get("data")
        json_data = dict(**kwargs).get("json")
        params = dict(**kwargs).get("params")
        headers = dict(**kwargs).get("headers")
        if data is not None:
            getlog.info(
                "接口的参数是：>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n{}".format(json.dumps(data, indent=2, ensure_ascii=False)))
        if json_data is not None:
            getlog.info(
                "接口的参数是：>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n{}".format(json.dumps(json_data, indent=2, ensure_ascii=False)))
        if params is not None:
            getlog.info(
                "接口的参数是：>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n{}".format(json.dumps(params, indent=2, ensure_ascii=False)))
        if headers is not None:
            getlog.info(
                "接口的headers是：>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n{}".format(
                    json.dumps(headers, indent=2, ensure_ascii=False)))
